//
//  MGMarqueeLabel.m
//  Live
//
//  Created by 胡超 on 2021/3/7.
//  Copyright © 2021 DLive. All rights reserved.
//

#import "MGMarqueeLabel.h"
#import "UIView+Mango.h"

@interface MGMarqueeRoundTripLabel () {
    UILabel *_contentLabel;
    BOOL _startControl;
}
@end

@implementation MGMarqueeRoundTripLabel

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
        self.speed = 30.0;
        self.stayDuration = 2;
    }
    return self;
}

- (UILabel *)contentLabel {
    if (_contentLabel == nil) {
        _contentLabel = [[UILabel alloc] init];
        [self addSubview:_contentLabel];
    }
    return _contentLabel;
}

- (void)setText:(NSString *)text {
    self.contentLabel.text = text;
}

- (void)setTextColor:(UIColor *)textColor {
    self.contentLabel.textColor = textColor;
}

- (void)setFont:(UIFont *)font {
    self.contentLabel.font = font;
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    self.contentLabel.attributedText = attributedText;
}

- (void)contentLabelSizeToFit {
    [self.contentLabel sizeToFit];
    [self.contentLabel setLeft:0];
    [self.contentLabel setCenterY:self.height/2];
}

- (void)clean {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateAnimation) object:nil];
}

- (void)startMarquee {
    [self contentLabelSizeToFit];
    
    if (self.contentLabel.width <= self.width) {
        [self.contentLabel.layer removeAllAnimations];
        return;
    }
    
    if (_startControl) {
        return;
    }
    
    _startControl = YES;
    CGFloat distance = self.contentLabel.width-self.width;
    CGFloat duration = distance/self.speed;
    CGFloat totalDuration = 2*duration+2*self.stayDuration;
    
    CGFloat keyTime0 = 0.0;
    CGFloat keyTime1 = duration/totalDuration;
    CGFloat keyTime2 = keyTime1 + self.stayDuration/totalDuration;
    CGFloat keyTime3 = keyTime2 + keyTime1;
    CGFloat keyTime4 = keyTime3 + self.stayDuration/totalDuration;
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
    anim.values = @[@(0), @(-distance), @(-distance), @(0), @(0)];
    anim.keyTimes = @[@(keyTime0),@(keyTime1),@(keyTime2),@(keyTime3),@(keyTime4)];
    anim.duration = totalDuration;
    anim.repeatCount = MAXFLOAT;
    anim.delegate = self;
    [self.contentLabel.layer addAnimation:anim forKey:nil];
    
    if (self.autoUpdateAnimation) {
        [self performSelector:@selector(updateAnimation) withObject:nil afterDelay:totalDuration];
    }
}

- (void)updateAnimation {
    _startControl = NO;
    [self startMarquee];
}

@end
